﻿namespace KeRui.Common
{
    using System;
    using System.Collections;

    public class Arithmetic
    {
        private CalUtility cu;
        private ArrayList HList = new ArrayList();
        private OperFactory of = new OperFactory();
        public ArrayList Vlist = new ArrayList();

        public Arithmetic(string str)
        {
            this.cu = new CalUtility(str);
        }

        private void Cal(string str)
        {
            if (!str.Equals("") || (this.HList.Count != 0))
            {
                if ((this.HList.Count > 0) && (this.Vlist.Count > 1))
                {
                    if (this.HList[this.HList.Count - 1].ToString().Equals("(") && str.Equals(")"))
                    {
                        this.HList.RemoveAt(this.HList.Count - 1);
                        if (this.HList.Count > 0)
                        {
                            str = this.HList[this.HList.Count - 1].ToString();
                            this.Cal(str);
                        }
                    }
                    else if (this.cu.Compare(this.HList[this.HList.Count - 1].ToString(), str))
                    {
                        IOper oper = this.of.CreateOper(this.HList[this.HList.Count - 1].ToString());
                        if (oper != null)
                        {
                            this.Vlist[this.Vlist.Count - 2] = oper.Oper(this.Vlist[this.Vlist.Count - 2], this.Vlist[this.Vlist.Count - 1]);
                            this.HList.RemoveAt(this.HList.Count - 1);
                            this.Vlist.RemoveAt(this.Vlist.Count - 1);
                            this.Cal(str);
                        }
                    }
                    else if (!str.Equals(""))
                    {
                        this.HList.Add(str);
                    }
                }
                else if (!str.Equals(""))
                {
                    this.HList.Add(str);
                }
            }
        }

        public object DoCal()
        {
            string c = this.cu.getItem();
            while (true)
            {
                if (this.cu.IsNum(c))
                {
                    this.Vlist.Add(c);
                }
                else
                {
                    this.Cal(c);
                }
                if (c.Equals(""))
                {
                    return this.Vlist[0];
                }
                c = this.cu.getItem();
            }
        }
    }
}

